/**
 * post请求方式
 * @author xiaoqiang <465633678@qq.com>
 * @created 2018/11/01 14:59:42
 */
const Koa = require('koa')
const app = new Koa()

app.use(async (ctx) => {
  /**
   * 判断路由地址是否是首页
   * 并且请求方式为get
   */
  if (ctx.url === '/' && ctx.method === 'GET') {
    ctx.body = `
      <html>
        <head>
          <title>标题</title>
        </head>
        <body>
          <form action="/" method="post">
            <div>
              用户名：
              <input value="" name="username" />
            </div>
            <div>
              密码：
              <input value="" name="password" />
            </div>
            <button type="submit">提交</button>
          </form>
        </body>
      </html>
    `
  } else if (ctx.url === '/' && ctx.method === 'POST') {
    const postData = await parsePostData(ctx)
    ctx.body = postData
  }
}).listen(9999)

/**
 * 转换post数据
 * @param {Object} ctx 
 */
function parsePostData(ctx) {
  return new Promise((resolve, reject) => {
    try {
      let postdata = "";
      ctx.req.addListener('data', (data) => {
        postdata += data
      })
      ctx.req.addListener('end', () => {
        postObject = parseQueryString(postdata)
        resolve(postObject)
      })
    } catch(e) {
      reject(e)
    }
  })
}

/**
 * 把queryString转换为query对象
 * @param {String} data 
 */
function parseQueryString(data) {
  const postData = {}
  /**
   * 通过&分割
   */
  const postDataList = data.split('&')
  postDataList.forEach(v => {
    /**
     * 通过=分割
     */
    const item = v.split('=')
    postData[item[0]] = decodeURIComponent(item[1]) || ''
  })
  return postData
}